package com.free.picture.ecognition.baidu;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.util.Util;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;

public class Sample {
    //设置APPID/AK/SK
    public static final String APP_ID = "104640814";
    public static final String API_KEY = "8hT1F5NHD2SXw1iwaH9gz6kN";
    public static final String SECRET_KEY = "OhIjZ2do9mAWQRKENOdTnHgf72lMC0cl";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String []args) throws IOException{
//        extracted();
        getResult();
    }

    private static void extracted() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"speech_url\":\"http://yhl.zone//statics/Note/uploadTmp/2024/08/06/20240806002221-%E3%80%90%E7%AC%AC11%E8%AF%BE%E3%80%91%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E8%81%8A%E5%A4%A9%E4%B8%AD%E7%8E%A9%E7%AC%91%E5%BC%80%E8%BF%87%E5%A4%B4%E7%9A%84%E5%B0%B4%E5%B0%AC%EF%BC%9F.mp3\",\"format\":\"mp3\",\"pid\":80001,\"rate\":16000}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/create?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());
    }

    public static void getResult() throws IOException{
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"task_ids\":[\"66b4dd0db647c30001856ad4\"]}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/query?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ResponseBody responseBody = response.body();
        String string = responseBody.string();
        System.out.println(string);
        StringBuilder result=new StringBuilder();
        JSONUtil.parseObj(string).getJSONArray("tasks_info").forEach(e -> {
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(e);
            JSONArray jsonArray = jsonObject.getJSONObject("task_result").getJSONArray("detailed_result");
            jsonArray.forEach(str -> {
                result.append(JSONUtil.parseObj(str).getJSONArray("res").get(0));
            });
        });
        System.out.println(result);
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}